package com.itc.dispatch.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itc.common.core.constant.CacheConstants;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.LocalDateTimeUtils;
import com.itc.common.core.utils.OkHttpUtil;
import com.itc.common.redis.service.RedisService;
import com.itc.dispatch.common.Constents;
import com.itc.dispatch.common.FindAndProcessParent;
import com.itc.dispatch.domain.AlarmCentre;
import com.itc.dispatch.domain.AlarmConfig;
import com.itc.dispatch.domain.AlarmRule;
import com.itc.dispatch.domain.AvoidFeign;
import com.itc.dispatch.domain.dto.AlarmConfigDto;
import com.itc.dispatch.domain.dto.AlarmConfigPageDto;
import com.itc.dispatch.domain.dto.DataSetDto;
import com.itc.dispatch.domain.dto.TriggerDto;
import com.itc.dispatch.domain.vo.AlarmConfigVo;
import com.itc.dispatch.domain.vo.FieldDataVo;
import com.itc.dispatch.service.AlarmCentreService;
import com.itc.dispatch.service.AlarmConfigService;
import com.itc.dispatch.mapper.AlarmConfigMapper;
import com.itc.dispatch.service.AlarmRuleService;
import com.itc.dispatch.service.AvoidFeignService;
import com.itc.system.api.RemoteSystemService;
import com.itc.system.api.domain.SysDept;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author 智少
* @description 针对表【alarm_config】的数据库操作Service实现
* @createDate 2024-07-24 15:38:12
*/
@Service
public class AlarmConfigServiceImpl extends ServiceImpl<AlarmConfigMapper, AlarmConfig>
    implements AlarmConfigService{

    @Value("${bi.httpUrl}")
    private String biHttpUrl;

    @Autowired
    private AlarmRuleService alarmRuleService;

    @Resource
    public RemoteSystemService remoteSystemService;

    @Autowired
    @Lazy
    public AlarmCentreService alarmCentreService;

    @Autowired
    public FindAndProcessParent findAndProcessParent;

    @Resource
    private RedisService redisService;


    @Override
    @Transactional
    public R add(AlarmConfigDto dto) {
        List<AlarmRule> alarmRules = dto.getAlarmRules();
        //首先判断基本内容重复
        LambdaQueryWrapper<AlarmConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlarmConfig::getAlarmType,dto.getAlarmType());
        wrapper.eq(AlarmConfig::getAlarmName,dto.getAlarmName());
        Long aLong = this.baseMapper.selectCount(wrapper);
        if (aLong > 0){
            return R.fail("同类型下告警配置名称重复");
        }
        AlarmConfig config = new AlarmConfig();
        BeanUtils.copyProperties(dto,config);
        //新增配置
        config.setCreateDate(LocalDateTime.now().toString());
        this.baseMapper.insert(config);
        String now = LocalDateTime.now().toString();
        alarmRules.forEach(alarmRule -> {
            alarmRule.setAcId(config.getId());
            alarmRule.setCreateDate(now);
            alarmRule.setDelete(0);
            alarmRule.setIsSolve(0);
        });
        //批量插入
        if (alarmRules.size() > Constents.Int_0){
            alarmRuleService.saveBatch(alarmRules);
        }
        return R.ok("新增成功");
    }

    @Override
    @Transactional
    public R delete(Long id) {
        AlarmConfig config = this.baseMapper.selectById(id);
        if (config == null){
            return R.fail("配置信息异常");
        }
        //告警有已触发的规则，则不允许删除
        LambdaQueryWrapper<AlarmCentre> centreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        centreLambdaQueryWrapper.eq(AlarmCentre::getDelete,0);
        centreLambdaQueryWrapper.eq(AlarmCentre::getConfigId,config.getId());
        Long list = alarmCentreService.count(centreLambdaQueryWrapper);
        if (list > 0){
            return R.fail("该告警管理已有规则触发，不允许删除");
        }
        //逻辑删除
        alarmRuleService.update(new LambdaUpdateWrapper<AlarmRule>().eq(AlarmRule::getAcId,config.getId()).set(AlarmRule::getDelete,1));
        config.setDelete(1);
        this.baseMapper.updateById(config);
        return R.ok("删除成功");
    }

    @Override
    @Transactional
    public R updateOne(AlarmConfigDto dto) {
        List<AlarmRule> alarmRules = dto.getAlarmRules();
        AlarmConfig alarmConfig = this.baseMapper.selectById(dto.getId());
        if (alarmConfig == null){
            return R.fail("告警管理数据有误");
        }
        LambdaQueryWrapper<AlarmRule> ruleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ruleLambdaQueryWrapper.eq(AlarmRule::getAcId,dto.getId());
        ruleLambdaQueryWrapper.eq(AlarmRule::getIsSolve,1);
        ruleLambdaQueryWrapper.eq(AlarmRule::getDelete,0);
        Long list = alarmRuleService.count(ruleLambdaQueryWrapper);
        if (list > 0){
            return R.fail("已有规则触发，无法更新该配置");
        }
        if (!Objects.equals(alarmConfig.getAlarmType(), dto.getAlarmType()) || !Objects.equals(alarmConfig.getAlarmName(), dto.getAlarmName())){
            LambdaQueryWrapper<AlarmConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AlarmConfig::getAlarmName,dto.getAlarmName());
            wrapper.eq(AlarmConfig::getAlarmType,dto.getAlarmType());
            Long aLong = this.baseMapper.selectCount(wrapper);
            if (aLong > 0){
                return R.fail("告警配置重复");
            }
        }
        BeanUtils.copyProperties(dto,alarmConfig);
        alarmConfig.setUpdateDate(LocalDateTime.now().toString());
        this.baseMapper.updateById(alarmConfig);
        //更新关联规则
        //删除规则
        alarmRuleService.update(new LambdaUpdateWrapper<AlarmRule>().eq(AlarmRule::getAcId,dto.getId()).set(AlarmRule::getDelete,1));
        //2.新增管理规则数据
        LocalDateTime now = LocalDateTime.now();
        alarmRules.forEach(alarmRule->{
            alarmRule.setId(null);
            alarmRule.setAcId(dto.getId());
            alarmRule.setCreateDate(now.toString());
            alarmRule.setDelete(0);
        });
        alarmRuleService.saveBatch(alarmRules);
        return R.ok("编辑成功");
    }

    @Override
    @Transactional
    public R<Page<AlarmConfigVo>> getPage(Page page,AlarmConfigPageDto pageDto) {
        LambdaQueryWrapper<AlarmConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(pageDto.getAlarmName()),AlarmConfig::getAlarmName,pageDto.getAlarmName())
                .eq(StringUtils.isNotBlank(pageDto.getAlarmType()),AlarmConfig::getAlarmType,pageDto.getAlarmType())
                .eq(pageDto.getStatus() != null,AlarmConfig::getStatus,pageDto.getStatus())
                .eq(AlarmConfig::getDelete,Constents.Int_0);
        Page<AlarmConfig> resultPage = this.baseMapper.selectPage(page, wrapper);
        //创建AlarmConfigVoPage对象
        Page<AlarmConfigVo> alarmConfigVoPage = new Page<>();
        alarmConfigVoPage.setCurrent(resultPage.getCurrent());
        alarmConfigVoPage.setSize(resultPage.getSize());
        alarmConfigVoPage.setTotal(resultPage.getTotal());
        ArrayList<AlarmConfigVo> alarmConfigVoArrayList = new ArrayList<>();
        for (AlarmConfig record : resultPage.getRecords()) {
            AlarmConfigVo alarmConfigVo = new AlarmConfigVo();
            BeanUtils.copyProperties(record,alarmConfigVo);
            //加入规则数据
            LambdaQueryWrapper<AlarmRule> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AlarmRule::getAcId,record.getId());
            queryWrapper.eq(AlarmRule::getDelete,0);
            List<AlarmRule> list = alarmRuleService.list(queryWrapper);
            alarmConfigVo.setAlarmRules(list);
            alarmConfigVoArrayList.add(alarmConfigVo);
        }
        alarmConfigVoPage.setRecords(alarmConfigVoArrayList);
        return R.ok(alarmConfigVoPage);
    }

    @Override
    public R<AlarmConfigVo> detail(Long id) {
        AlarmConfigVo alarmConfigVo = new AlarmConfigVo();
        AlarmConfig config = this.baseMapper.selectById(id);
        if (config == null){
            return R.fail("配置信息异常");
        }
        BeanUtils.copyProperties(config,alarmConfigVo);
        //加入规则数据
        LambdaQueryWrapper<AlarmRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlarmRule::getAcId,id);
        queryWrapper.eq(AlarmRule::getDelete,0);
        List<AlarmRule> list = alarmRuleService.list(queryWrapper);
        alarmConfigVo.setAlarmRules(list);
        return R.ok(alarmConfigVo);
    }

    @Override
    @Transactional
    public R change( Long id) {
        AlarmConfig config = this.baseMapper.selectById(id);
        if (config == null){
            return R.fail("数据有误");
        }
        LambdaQueryWrapper<AlarmCentre> centreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        centreLambdaQueryWrapper.eq(AlarmCentre::getConfigId,config.getId());
        centreLambdaQueryWrapper.eq(AlarmCentre::getDelete,0);
        if (config.getStatus().intValue() == Constents.Int_0){
            config.setStatus(1);
            //开启当前告警数据，所有该触发的告警中心数据变为待确认
            centreLambdaQueryWrapper.eq(AlarmCentre::getAlarmStatus,4);
            List<AlarmCentre> list = alarmCentreService.list(centreLambdaQueryWrapper);
            list.forEach(one -> one.setAlarmStatus(0));
            alarmCentreService.saveOrUpdateBatch(list);
            this.baseMapper.updateById(config);
            return R.ok("修改成功");
        }else {
            //关闭当前告警，所有该触发的告警中心数据变为已关闭
            config.setStatus(0);
            this.baseMapper.updateById(config);
            // 设置状态为 4,已关闭
            centreLambdaQueryWrapper.eq(AlarmCentre::getAlarmStatus,0);
            List<AlarmCentre> list = alarmCentreService.list(centreLambdaQueryWrapper);
            list.forEach(one -> one.setAlarmStatus(4));
            alarmCentreService.saveOrUpdateBatch(list);
            return R.ok(null,"修改成功");
        }
    }

    @Override
    @Transactional
    public R trigger(TriggerDto dto) {
        AlarmConfig config = this.baseMapper.selectById(dto.getId());
        if (config == null){
            return R.fail("该条触发数据有误");
        }
        //查询当前处置下的告警id
        if (dto.getCenterId() != null){
            AlarmCentre cruAlarmCentre = alarmCentreService.getById(dto.getCenterId());
            if (cruAlarmCentre == null){
                return R.fail("当前告警中心数据有误");
            }
            String alarmIds = cruAlarmCentre.getAlarmIds();
            cruAlarmCentre.setAlarmIds(alarmIds+","+dto.getId());
            alarmCentreService.updateById(cruAlarmCentre);
        }
        //修改当前告警数据
        config.setIsCentreTrigger(1);
        this.baseMapper.updateById(config);
        //添加告警中心数据
        AlarmCentre alarmCentre = new AlarmCentre();
        alarmCentre.setAlarmTime(LocalDateTimeUtils.getCurrentLocalDateTime());
        alarmCentre.setAlarmStatus(0);
        alarmCentre.setTriggerByType(0);
        alarmCentre.setDelete(0);
        alarmCentre.setConfigId(config.getId());
        alarmCentre.setIsTop(1);
        alarmCentre.setAlarmGrade(dto.getAlarmGrade());
        alarmCentre.setAlarmMsg(dto.getAlarmMsg());
        alarmCentre.setAlarmType(config.getAlarmType());
        alarmCentre.setAlarmName(config.getAlarmName());
        alarmCentre.setConfirmIds(config.getConfirmIds());
        alarmCentre.setAlarmIds(config.getAlarmIds());
        alarmCentreService.save(alarmCentre);
        return R.ok(null,"手动触发成功");
    }

    @Override
    public R<List<AlarmConfigDto>> getAlarmData() {
        List<AlarmConfigDto> alarmConfigVoList = this.baseMapper.selectAlarmData();
        return R.ok(alarmConfigVoList);
    }


    @Override
    public void alarmTriggerTask() {
        //当前可用的告警规则信息列表（配置处于启用状态）
        List<AlarmRule> ruleList = this.baseMapper.getConfigAvailableRuleList();
        if(ruleList.size() == 0){
            return;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        Map<String,List<AlarmRule>> apiRuleMap = ruleList.stream().collect(Collectors.groupingBy(AlarmRule::getApiIdentifier));
        for (String apiId : apiRuleMap.keySet()) {
            //查询对应数据集及数据信息
            JSONObject param = new JSONObject();
            param.put("apiIdentifier",apiId);
            param.put("pageSize",10000);
            param.put("pageIndex",1);

            RequestBody body = RequestBody.create(JSON.toJSONString(param), MediaType.get("application/json"));
            Object resultData = OkHttpUtil.sendOkHttpClient(biHttpUrl + "/bi/openApi/query","POST", body, null);
            if(resultData == null){
                continue;
            }
            JSONObject dataJson = JSONObject.parseObject(resultData.toString());
            if(dataJson.get("code") == null || dataJson.getIntValue("code") != 200 || dataJson.get("data") == null
                    || dataJson.getJSONObject("data").get("dataList") == null){
                continue;
            }
            JSONArray dataList = dataJson.getJSONObject("data").getJSONArray("dataList");
            if(dataList.size() == 0){
                continue;
            }
            List<AlarmRule> tigRuleList = apiRuleMap.get(apiId);
            for (AlarmRule alarmRule : tigRuleList) {
                if(alarmRule.getCondition() == null){
                    continue;
                }
                int condition = alarmRule.getCondition();
                String uniqueDataKey = alarmRule.getUniqueDataKey();
                String conditionValue = alarmRule.getConditionValue();
                String fieldKey = alarmRule.getFieldKey();
                int alarmType = alarmRule.getAlarmType();
                for (Object o : dataList) {
                    //进行数据规则校验
                    JSONObject detailJson = JSONObject.parseObject(o.toString());
                    String fieldValue = detailJson.getString(fieldKey);
                    String uniqueDataValue = detailJson.getString(uniqueDataKey);
                    if(fieldValue == null || uniqueDataValue == null){
                        continue;
                    }
                    Boolean checkStatus = true;
                    if(alarmType == 1){
                        //指标类型
                        BigDecimal value = new BigDecimal(fieldValue);
                        if(condition == 6){
                            //包含，需要在左右值区间内
                            BigDecimal leftValue = new BigDecimal(String.valueOf(alarmRule.getLeftValue()));
                            BigDecimal rightValue = new BigDecimal(String.valueOf(alarmRule.getRightValue()));
                            if(alarmRule.getIndexLeftTail().intValue() == 0){
                                if(value.compareTo(leftValue) <= 0){
                                    checkStatus = false;
                                }
                            }else{
                                if(value.compareTo(leftValue) < 0){
                                    checkStatus = false;
                                }
                            }
                            if(alarmRule.getIndexRightTail().intValue() == 0){
                                if(value.compareTo(rightValue) >= 0){
                                    checkStatus = false;
                                }
                            }else{
                                if(value.compareTo(rightValue) > 0){
                                    checkStatus = false;
                                }
                            }
                        }else if(condition == 7){
                            //包含，需要在左右值区间外
                            BigDecimal leftValue = new BigDecimal(String.valueOf(alarmRule.getLeftValue()));
                            BigDecimal rightValue = new BigDecimal(String.valueOf(alarmRule.getRightValue()));
                            if(alarmRule.getIndexLeftTail().intValue() == 0){
                                if(value.compareTo(leftValue) >= 0){
                                    checkStatus = false;
                                }
                            }else{
                                if(value.compareTo(leftValue) > 0){
                                    checkStatus = false;
                                }
                            }
                            if(alarmRule.getIndexRightTail().intValue() == 0){
                                if(value.compareTo(rightValue) <= 0){
                                    checkStatus = false;
                                }
                            }else{
                                if(value.compareTo(rightValue) < 0){
                                    checkStatus = false;
                                }
                            }
                        }else{
                            //其他类型需要根据对比类型来校验对比结果
                            BigDecimal checkValue = new BigDecimal(conditionValue);
                            if(condition == 0){
                                if(value.compareTo(checkValue) != 0){
                                    checkStatus = false;
                                }
                            }else if(condition == 1){
                                if(value.compareTo(checkValue) >= 0){
                                    checkStatus = false;
                                }
                            }else if(condition == 2){
                                if(value.compareTo(checkValue) <= 0){
                                    checkStatus = false;
                                }
                            }else if(condition == 3){
                                if(value.compareTo(checkValue) < 0){
                                    checkStatus = false;
                                }
                            }else if(condition == 4){
                                if(value.compareTo(checkValue) > 0){
                                    checkStatus = false;
                                }
                            }else if(condition == 5){
                                if(value.compareTo(checkValue) == 0){
                                    checkStatus = false;
                                }
                            }else{
                                checkStatus = false;
                            }
                        }
                    }else if(alarmType == 2){
                        //时间跳变类型
                        String redisKey = CacheConstants.ALARM_CONFIG_BI_DATA_CACHE+apiId+":"+uniqueDataKey+":"+uniqueDataValue;
                        String str = redisService.getCacheObject(redisKey);
                        redisService.setCacheObject(redisKey,fieldValue,1L, TimeUnit.MINUTES);
                        if(str == null){
                            //没取到缓存，说明是第一次触发，不需要校验
                            continue;
                        }
                        LocalDateTime valueTime = LocalDateTime.parse(fieldValue,formatter);
                        LocalDateTime lastTime = LocalDateTime.parse(str,formatter);
                        int timeUnit = alarmRule.getTimeUnit();
                        BigDecimal conditionValueBig = new BigDecimal(conditionValue);

                        if(condition == 8){
                            //往前跳变（包含）
                            if(valueTime.isAfter(lastTime)){
                                checkStatus = false;
                            }else{
                                Duration duration = Duration.between(valueTime, lastTime);
                                if(timeUnit == 0){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 1){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 2){
                                    if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 3){
                                    if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else{
                                    checkStatus = false;
                                }
                            }
                        }else if(condition == 9){
                            //往前跳变（不包含）
                            if(valueTime.isAfter(lastTime)){
                                checkStatus = false;
                            }else{
                                Duration duration = Duration.between(valueTime, lastTime);
                                if(timeUnit == 0){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 1){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 2){
                                    if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 3){
                                    if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else{
                                    checkStatus = false;
                                }
                            }
                        }else if(condition == 10){
                            //往后跳变（包含）
                            if(valueTime.isBefore(lastTime)){
                                checkStatus = false;
                            }else{
                                Duration duration = Duration.between(lastTime, valueTime);
                                if(timeUnit == 0){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 1){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 2){
                                    if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 3){
                                    if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) > 0){
                                        checkStatus = false;
                                    }
                                }else{
                                    checkStatus = false;
                                }
                            }
                        }else if(condition == 11){
                            //往后跳变（不包含）
                            if(valueTime.isBefore(lastTime)){
                                checkStatus = false;
                            }else{
                                Duration duration = Duration.between(lastTime, valueTime);
                                if(timeUnit == 0){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 1){
                                    if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 2){
                                    if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else if(timeUnit == 3){
                                    if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) <= 0){
                                        checkStatus = false;
                                    }
                                }else{
                                    checkStatus = false;
                                }
                            }
                        }else{
                            checkStatus = false;
                        }
                    }else{
                        //文本类型
                        if(condition == 0){
                            //等于
                            if(!fieldValue.equals(conditionValue)){
                                checkStatus = false;
                            }
                        }else if(condition == 5){
                            //不等于
                            if(fieldValue.equals(conditionValue)){
                                checkStatus = false;
                            }
                        }else if(condition == 6){
                            //包含
                            if(fieldValue.indexOf(conditionValue) < 0){
                                checkStatus = false;
                            }
                        }else if(condition == 7){
                            //不包含
                            if(fieldValue.indexOf(conditionValue) > -1){
                                checkStatus = false;
                            }
                        }else if(condition == 12){
                            //跳变
                            String redisKey = CacheConstants.ALARM_CONFIG_BI_DATA_CACHE+apiId+":"+uniqueDataKey+":"+uniqueDataValue;
                            String str = redisService.getCacheObject(redisKey);
                            redisService.setCacheObject(redisKey,fieldValue,1L,TimeUnit.MINUTES);
                            if(str == null){
                                //没取到缓存，说明是第一次触发，不需要校验
                                continue;
                            }
                            if(fieldValue.equals(str)){
                                checkStatus = false;
                            }
                        }else{
                            checkStatus = false;
                        }
                    }

                    if(!checkStatus){
                        //条件不满足
                        continue;
                    }

                    //判断是否需要重复触发
                    if(alarmRule.getUnconfirmIspush().intValue() == 1 || alarmRule.getConfirmIspush().intValue() == 1){
                        //查询规则数据上一次告警信息
                        AlarmCentre lastAlarm = alarmCentreService.getBaseMapper().selectOne(
                                new LambdaQueryWrapper<AlarmCentre>()
                                        .eq(AlarmCentre::getTablesName,apiId)
                                        .in(AlarmCentre::getAlarmStatus,new Integer[]{1,0})
                                        .eq(AlarmCentre::getRuId,alarmRule.getId())
                                        .eq(AlarmCentre::getUniqueDataValue,uniqueDataValue)
                                        .orderByDesc(AlarmCentre::getAlarmTime)
                                        .last("limit 1")
                        );
                        if(lastAlarm != null){
                            if(lastAlarm.getAlarmStatus().intValue() == 0){
                                //未确认
                                if(alarmRule.getUnconfirmIspushAgain().intValue() == 1){
                                    //反复推送需要校验时间间隔是否满足
                                    LocalDateTime lastTime = LocalDateTime.parse(lastAlarm.getAlarmTime(),formatter);
                                    LocalDateTime current = LocalDateTime.now();
                                    Duration duration = Duration.between(lastTime, current);
                                    if(alarmRule.getUnconfirmIspush().intValue() != 0){
                                        int timeUnit = Integer.parseInt(alarmRule.getUnagainTimeUnit());
                                        BigDecimal conditionValueBig = new BigDecimal(String.valueOf(alarmRule.getUnagainTimeValue()));
                                        if(timeUnit == 0){
                                            if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 1){
                                            if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 2){
                                            if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 3){
                                            if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }
                                    }
                                }else{
                                    Long count = alarmCentreService.getBaseMapper().selectCount(
                                            new LambdaQueryWrapper<AlarmCentre>()
                                                    .eq(AlarmCentre::getAlarmStatus,0)
                                                    .eq(AlarmCentre::getTablesName,apiId)
                                                    .eq(AlarmCentre::getRuId,alarmRule.getId())
                                                    .eq(AlarmCentre::getUniqueDataValue,uniqueDataValue)
                                    );
                                    if(count > 1){
                                        //说明已经重复推送过了，不需要再次推送
                                        continue;
                                    }
                                }
                            }else{
                                //已确认
                                if(alarmRule.getConfirmIspushAgain().intValue() == 1){
                                    //反复推送需要校验时间间隔是否满足
                                    LocalDateTime lastTime = LocalDateTime.parse(lastAlarm.getAlarmTime(),formatter);
                                    LocalDateTime current = LocalDateTime.now();
                                    Duration duration = Duration.between(lastTime, current);
                                    if(alarmRule.getConfirmIspushAgain().intValue() != 0){
                                        int timeUnit = Integer.parseInt(alarmRule.getAgainTimeUnit());
                                        BigDecimal conditionValueBig = new BigDecimal(String.valueOf(alarmRule.getAgainTimeValue()));
                                        if(timeUnit == 0){
                                            if(new BigDecimal(String.valueOf(duration.getSeconds()*1000)).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 1){
                                            if(new BigDecimal(String.valueOf(duration.getSeconds())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 2){
                                            if(new BigDecimal(String.valueOf(duration.toMinutes())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }else if(timeUnit == 3){
                                            if(new BigDecimal(String.valueOf(duration.toHours())).compareTo(conditionValueBig) >= 0){
                                                continue;
                                            }
                                        }
                                    }
                                }else{
                                    Long count = alarmCentreService.getBaseMapper().selectCount(
                                            new LambdaQueryWrapper<AlarmCentre>()
                                                    .eq(AlarmCentre::getAlarmStatus,1)
                                                    .eq(AlarmCentre::getTablesName,apiId)
                                                    .eq(AlarmCentre::getRuId,alarmRule.getId())
                                                    .eq(AlarmCentre::getUniqueDataValue,uniqueDataValue)
                                    );
                                    if(count > 1){
                                        //说明已经重复推送过了，不需要再次推送
                                        continue;
                                    }
                                }
                            }
                        }
                    }

                    //判断当前规则下，该条数据是否已经存在更高等级的告警，如果存在，则不触发，不存在，则将所有历史数据状态变成下级告警，当前数据为上级告警
                    List<AlarmCentre> topList = alarmCentreService.getBaseMapper().selectList(
                            new LambdaQueryWrapper<AlarmCentre>()
                            .eq(AlarmCentre::getRuId,alarmRule.getId())
                            .eq(AlarmCentre::getTablesName,alarmRule.getApiIdentifier())
                            .eq(AlarmCentre::getUniqueDataValue,uniqueDataValue)
                            .orderByAsc(AlarmCentre::getAlarmGrade)
                            .orderByDesc(AlarmCentre::getAlarmTime)
                    );
                    AlarmCentre alarmCentre = new AlarmCentre();
                    if(topList.size() > 0){
                        //更新所有历史数据为下级
                        alarmCentreService.update(
                                new LambdaUpdateWrapper<AlarmCentre>()
                                .set(AlarmCentre::getIsTop,0)
                                .eq(AlarmCentre::getRuId,alarmRule.getId())
                                .eq(AlarmCentre::getTablesName,alarmRule.getApiIdentifier())
                                .eq(AlarmCentre::getUniqueDataValue,uniqueDataValue)
                        );
                        //将等级最高的告警置为上级
                        alarmCentre = topList.get(0);
                        alarmCentre.setIsTop(1);
                    }else{
                        alarmCentre.setAlarmName(alarmRule.getAlarmName());
                        alarmCentre.setAlarmType(alarmRule.getConfigAlarmType());
                        alarmCentre.setAlarmTime(LocalDateTimeUtils.getCurrentLocalDateTime());
                        alarmCentre.setAlarmGrade(alarmRule.getAlarmGrade());
                        alarmCentre.setAlarmMsg(alarmRule.getDescribe());
                        alarmCentre.setAlarmStatus(0);
                        alarmCentre.setRuId(alarmRule.getId());
                        alarmCentre.setTablesName(alarmRule.getApiIdentifier());
                        alarmCentre.setFieldName(alarmRule.getFieldKey());
                        alarmCentre.setTriggerByType(1);
                        alarmCentre.setDelete(0);
                        alarmCentre.setIsTop(1);
                        alarmCentre.setConfirmIds(alarmRule.getConfirmIds());
                        alarmCentre.setFlowIds(alarmRule.getFlowIds());
                        alarmCentre.setConfigId(alarmRule.getAcId());
                        alarmCentre.setUniqueDataValue(uniqueDataValue);
                    }
                    alarmCentreService.getBaseMapper().insert(alarmCentre);
                }
            }
        }

    }
}




